package com.jintoufs.service.security.impl;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import com.jintoufs.util.resource.Node;
import com.jintoufs.util.resource.ResourceNodeTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jintoufs.dao.security.ResourceDAO;
import com.jintoufs.domain.security.Resource;
import com.jintoufs.service.security.ResourceService;
import com.jintoufs.util.ztree.TreeNode;

@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceDAO resourceDAO;

    @Override
    public Map<String, Object> save(Resource resource) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Integer id = resource.getId();
            if (id == null) {
                resourceDAO.insert(resource);
                result.put("msg", "新增成功");
            } else {
                resourceDAO.update(resource);
                result.put("msg", "更新成功");
            }
            result.put("status", "OK");
            return result;
        } catch (Exception e) {
            result.put("msg", "操作失败");
            result.put("status", "ERROR");
            return result;
        }
    }

    @Override
    public List<Resource> findByParams(Map<String, Object> params) {
        return resourceDAO.selectByParams(params);
    }

    @Override
    public void delete(Integer id) {
        resourceDAO.delete(id);
    }

    @Override
    public void deleteResourceByRole(Integer roleId) {
        resourceDAO.deleteResourceByRole(roleId);
    }

    @Override
    public void saveRoleResource(Integer roleId, Integer resourceId) {
        resourceDAO.saveRoleResource(roleId, resourceId);

    }

    @Override
    public List<Resource> selectByRole(Integer roleId) {
        return resourceDAO.selectByRole(roleId);
    }

    /**
     * 判断字符串包含某个字符的个数
     *
     * @param str1
     * @param str2
     * @return
     */
    private int getStringIndexOfNumber(String str1, String str2) {
        int counter = 0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        }
        while (str1.indexOf(str2) != -1) {
            counter++;
            str1 = str1.substring(str1.indexOf(str2) + str2.length());
        }
        return counter;
    }

    @Override
    public List<TreeNode> getModuleTree(Resource entity) {
        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("resourceType", "F");
        List<Resource> list = resourceDAO.selectByParams(params);
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        int num = 0;
        for (Resource tmp : list) {
            num = getStringIndexOfNumber(tmp.getParentIds(), "/");
            if (num <= 3) {
                nodes.add(buildModuleNode(tmp, entity));
            }
        }
        return nodes;
    }

    /**
     * 根据区域信息构建树节点 <br />
     * 区域信息代表的树节点原则上都是父节点,但可以没有子节点
     *
     * @return
     */
    private TreeNode buildModuleNode(Resource entity, Resource oldResource) {
        TreeNode areaNode = new TreeNode();
        areaNode.setId(String.valueOf(entity.getId()));
        areaNode.setName(entity.getResourceName());
        if (entity.getParentId() != null && entity.getParentId() != 0) {
            areaNode.setPId(String.valueOf(entity.getParentId()));
        } else {
            areaNode.setIsParent(true); // 处理无子节点的父节点
        }
        if (oldResource != null && oldResource.getParentId() == entity.getId()) {
            areaNode.setChecked(true);
        }
        areaNode.setOpen(false);
        return areaNode;
    }

    @Override
    public List<TreeNode> getResourceTreeByRole(Integer id) {
        Map<String, Object> params = new HashMap<String, Object>();
        List<Resource> list = resourceDAO.selectByParams(params);
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        /* 根据网点OID构建数据时,只需要两级即可(网点及其直接上级区域) */
        List<Resource> listResource = resourceDAO.selectByRole(id);
        for (Resource tmp : list) {
            nodes.add(buildNode(tmp, listResource));
        }
        return nodes;
    }

    @Override
    public void deleteResourceById(Integer id) {
        resourceDAO.deleteResourceById(id);
    }

    @Override
    public boolean isMenu(Map<String, Object> params) {
        return resourceDAO.isMenu(params);
    }

    /**
     * 根据区域信息构建树节点 <br />
     * 区域信息代表的树节点原则上都是父节点,但可以没有子节点
     *
     * @param
     * @return
     */
    private TreeNode buildNode(Resource entity, List<Resource> listResource) {
        TreeNode areaNode = new TreeNode();
        areaNode.setId(String.valueOf(entity.getId()));
        areaNode.setName(entity.getResourceName());
        if (entity.getParentId() != null && entity.getParentId() != 0) {
            areaNode.setPId(String.valueOf(entity.getParentId()));
        } else {
            areaNode.setIsParent(true); // 处理无子节点的父节点
        }
        areaNode.setOpen(false);
        for (Resource resource : listResource) {
            if (resource.getId() == entity.getId()) {
                areaNode.setChecked(true);
            }
        }
        return areaNode;
    }

    @Override
    public List<Object> getResourceTreeList(List<Resource> entity) {
        List<Resource> resourceList = (List<Resource>) ((ArrayList) entity).clone();
        List<Resource> list = new ArrayList<>();
        List<Node> nodes = new ArrayList<>();
        ResourceNodeTree resourceTree = new ResourceNodeTree();
        Map<Integer, Resource> map = new ConcurrentHashMap<>();
        while (resourceList.size() != 0) {
            Iterator<Resource> iterator = resourceList.iterator();
            while (iterator.hasNext()) {
                Resource resource = iterator.next();
                if (resource.getParentId() == 0) {
                    list.add(resource);
                    map.put(resource.getId(),resource);
                    iterator.remove();
                } else if (map.containsKey(resource.getParentId())) {
                    list.add(resource);
                    map.put(resource.getId(),resource);
                    iterator.remove();
                }
            }
        }
        for(Resource resource:list){
            nodes.add(new Node(resource.getId(),resource.getParentId(),resource));
        }
        ResourceNodeTree resourceNodeTree = resourceTree.createTree(nodes);
        resourceTree.firstOrder(resourceNodeTree.getRoot());
        return resourceTree.getFristList();
    }

}
